package com.me.mvc.controller;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import com.me.mvc.model.ModelUtils;
import com.me.mvc.model.entity.Transaction;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Roman Uholnikov
 */
@Controller
@RequestMapping("/transactions")
public class Transactions {

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView showAll(ModelMap model, @RequestParam( required = false, defaultValue = "0") int sender,
                                @RequestParam( required = false, defaultValue = "0") int receiver,
                                @RequestParam( required = false, defaultValue = "0.0") double sum) {


        if(receiver!= 0 && sender!=0){
            Transaction transaction = new Transaction(ModelUtils.transactionMap.lastKey()+1,
                    ModelUtils.accountMap.get(sender),
                    ModelUtils.accountMap.get(receiver),
                    sum,
                    new Date());
            ModelUtils.transactionMap.put(transaction.getId(), transaction);
        }
        return new ModelAndView("transactions", "transactions", new LinkedList<Transaction>(ModelUtils.transactionMap.values()));
    }

    @RequestMapping(value = "/byClient/{clientId}", method = RequestMethod.GET)
    public String showByClient(ModelMap model, @PathVariable("clientId") Integer clientId) {
        List<Transaction> transactionList = new LinkedList<Transaction>();
        for (Transaction transaction : ModelUtils.transactionMap.values()){

            if((transaction.getReceiverAccount().getClient().getId() == clientId)
                    || (transaction.getSenderAccount().getClient().getId() == clientId)){
                transactionList.add(transaction);
            }
        }
        model.addAttribute("transactions", transactionList);
        return "transactions";
    }

    @RequestMapping(value = "/byBank/{bankId}", method = RequestMethod.GET)
    public String showByBank(ModelMap model, @PathVariable("bankId") Integer bankId) {
        List<Transaction> transactionList = new LinkedList<Transaction>();
        for (Transaction transaction : ModelUtils.transactionMap.values()){
            if((transaction.getReceiverAccount().getBank().getId() == bankId)
                    || (transaction.getSenderAccount().getBank().getId() == bankId)){
                transactionList.add(transaction);
            }
        }
        model.addAttribute("transactions", transactionList);
        return "transactions";
    }
}
